package service

import (
	"context"
	"fmt"
	"tentx-srv/basic/config"
	__ "tentx-srv/basic/proto"
	"tentx-srv/handler/models"
)

type Server struct {
	__.UnimplementedTentxServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) TentVideoAdd(_ context.Context, in *__.TentVideoAddReq) (*__.TentVideoAddResp, error) {
	v := models.Video{
		Title:     in.Title,
		VideoUrl:  in.VideoUrl,
		ConUrl:    in.ConUrl,
		Status:    int(in.Status),
		Watchtime: int(in.Watchtime),
		UserId:    int(in.UserId),
	}
	if err := v.CreateVideo(config.DB); err != nil {
		return nil, err
	}
	return &__.TentVideoAddResp{
		Id: int64(v.ID),
	}, nil
}
func (s *Server) MemberAdd(_ context.Context, in *__.MemberAddReq) (*__.MemberAddResp, error) {
	v := models.Member{
		Price:   float64(in.Price),
		Status:  int(in.Status),
		VideoId: int(in.VideoId),
		UserId:  int(in.UserId),
	}
	tx := config.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	if err := tx.Error; err != nil {
		return nil, err
	}

	if err := tx.Error; err != nil {
		tx.Rollback()
		return nil, err
	}

	if err := tx.Commit().Error; err != nil {
		return nil, err
	}
	if err := v.MemberCreate(config.DB); err != nil {
		return nil, err
	}
	return &__.MemberAddResp{
		Id: int64(v.ID),
	}, nil
}

func (s *Server) TentVideoList(_ context.Context, in *__.TentListReq) (*__.TentListResp, error) {
	var v models.Video
	list, err := v.VideoFind(config.DB, int(in.Page), int(in.PageSize))
	if err != nil {
		return nil, fmt.Errorf("查询失败了")
	}
	return &__.TentListResp{
		Videol: list,
	}, nil
}

func (s *Server) MemberList(_ context.Context, in *__.MemberListReq) (*__.MemberListResp, error) {
	var v models.Member

	list, err := v.MemberFind()
	if err != nil {
		return nil, fmt.Errorf("查询失败了")
	}
	return &__.MemberListResp{
		List: list,
	}, nil
}

//
//func (s *Server) VideohistoryList(_ context.Context, in *__.HistoryListReq) (*__.HistoryListResp, error) {
//	var v models.Video
//
//	list, err := v.FindVideo(config.DB)
//	if err != nil {
//		return nil, fmt.Errorf("查询失败了")
//	}
//	return &__.HistoryListResp{
//		List: list,
//	}, nil
//}
